import { create } from "zustand";
import { login as loginApi, logout as logoutApi } from "@/api/login";
import {
  getToken,
  removeToken,
  setToken,
  getLoginHandle,
  removeLoginHandle,
  setLoginHandle,
} from "@/utils/auth";
import type { LoginData } from "@/api/login/types";

interface AuthState {
  token: string | null;
  loginHandle: number | null;
  setToken: (token: string | null) => void;
  clearToken: () => void;
  setLoginHandleValue: (handle: number | null) => void;
  clearLoginHandle: () => void;
  login: (userInfo: LoginData) => Promise<void>;
  logout: () => void;
}

const useAuthStore = create<AuthState>((set) => ({
  /* 令牌 */
  token: getToken(),
  loginHandle: getLoginHandle(),
  // 存储令牌
  setToken: (token) => {
    if (token) {
      setToken(token);
    } else {
      removeToken();
    }
    set({ token });
  },
  // 清除令牌
  clearToken: () => {
    removeToken();
    set({ token: null });
  },
  setLoginHandleValue: (handle: number | null) => {
    if (handle !== null) {
      setLoginHandle(handle);
    } else {
      removeLoginHandle();
    }
    set({ loginHandle: handle });
  },
  clearLoginHandle: () => {
    removeLoginHandle();
    set({ loginHandle: null });
  },
  // 登录
  login: async (userInfo: LoginData): Promise<void> => {
    try {
      const res = await loginApi(userInfo);
      console.log("【登录成功】", res);
      const data = res.data;
      const token = data.access_token;

      setToken(token);
      set({ token });

      return Promise.resolve();
    } catch (err) {
      return Promise.reject(err);
    }
  },
  logout: async () => {
    try {
      await logoutApi();
    } finally {
      removeToken();
      removeLoginHandle();
      set({ token: null, loginHandle: null }); // 🔑 确保登出后 store 更新
    }
  },
}));

export default useAuthStore;
